package com.nwpu.util;


import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.stereotype.Component;

import java.util.Random;


@Component
public class Md5Util {

        /**
         * 随机生成8位密码盐
         *
         * @return
         */
        public String getRandomSalt() {
            char[] chars = ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +
                    "1234567890").toCharArray();

            StringBuilder sb = new StringBuilder();
            sb.append("$1$");
            for (int i = 0; i < 5; i++) {
                //Random().nextInt()返回值为[0,n)
                char aChar = chars[new Random().nextInt(chars.length)];
                sb.append(aChar);
            }
            return sb.toString();
        }

        /**
         * 生成摘要
         *
         * @param password
         * @param salt
         * @return
         */
        public String encode(String password, String salt) {
            //使用指定盐值生成MD5
            String md5Password= Md5Crypt.md5Crypt(password.getBytes(), salt);
            return md5Password;
        }

    }